package com.liyl.service;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.write.metadata.WriteSheet;
import com.liyl.entity.Produce;
import com.liyl.util.ExportUtil;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.math.BigDecimal;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

@Service
public class ProduceService {

    public void exportExcel(HttpServletResponse response) throws IOException {
        List<Produce> produceList = allList();
        List<List<String>> heads = headsList();
        List<String> includeColumns = ExportUtil.fcstComparisonVoColumnsByOrder();
        List<List<Object>> datas = ExportUtil.getExportListDatas(produceList, includeColumns);
        // 这里注意 有同学反应使用swagger 会导致各种问题，请直接用浏览器或者用postman
        response.setContentType("application/vnd.ms-excel");
        response.setCharacterEncoding("utf-8");
        // 这里URLEncoder.encode可以防止中文乱码 当然和 easy excel 没有关系
        String fileName = URLEncoder.encode("测试", "UTF-8").replaceAll("\\+", "%20");
        response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + System.currentTimeMillis() + ".xlsx");
        EasyExcel.write(response.getOutputStream(),Produce.class).head(heads).sheet("模板").autoTrim(false).doWrite(datas);


    }

    private List<List<String>> headsList() {
        List<List<String>> lists = new ArrayList<>();
        lists.add(Arrays.asList("总分类"));
        lists.add(Arrays.asList("数值"));
        return lists;
    }

    private List<Produce> allList() {
        List<Produce> produceList = new ArrayList<>();
        produceList.add(new Produce("mtl group", BigDecimal.ZERO));
        produceList.add(new Produce("  mtl group a", BigDecimal.ZERO));
        produceList.add(new Produce("    mtl group 1", BigDecimal.ZERO));
        produceList.add(new Produce("    mtl group 2", BigDecimal.ZERO));
        produceList.add(new Produce("  mtl group b", BigDecimal.ZERO));
        produceList.add(new Produce("    mtl group 1", BigDecimal.ZERO));
        produceList.add(new Produce("    mtl group 2", BigDecimal.ZERO));
        return produceList;
    }
}
